import { menuCreateApi, menuGetDetailMenuIdApi, menuTreeApi, menuUpdateApi } from '@/apis/payment'
import { MenuDetailVO, MenuDTO } from '@/apis/payment.type'
import { BasicModal, BasicModalProps } from '@/components/BasicModal'
import useMessage from '@/hooks/useMessage'
import { tools } from '@/utils/tools'
import {
  ProFormDependency,
  ProFormDigit,
  ProFormInstance,
  ProFormSelect,
  ProFormSwitch,
  ProFormText,
  ProFormTextArea,
  ProFormTreeSelect
} from '@ant-design/pro-components'
import { useRequest } from 'ahooks'
import { Form } from 'antd'
import { set } from 'lodash-es'
import { useEffect } from 'react'

export default function UpdateMenuModal({ register, onFinished }: BasicModalProps) {
  const { visible, initialValues, onClose } = register()
  const [form] = Form.useForm<MenuDetailVO>()
  const { message } = useMessage()

  const { loading, data: menuDetail } = useRequest(getMenuDetail, {
    refreshDeps: [initialValues, visible]
  })

  const modalTitle = initialValues ? '编辑菜单' : '新增菜单'

  useEffect(() => {
    if (visible && menuDetail) {
      form.setFieldsValue(menuDetail)
    } else {
      form.resetFields()
    }
  }, [visible, menuDetail, form])

  async function getMenuDetail() {
    const menuId = initialValues?.menuId
    if (!menuId) return
    const { success, data } = await menuGetDetailMenuIdApi({ menuId })
    if (success) {
      return data
    }
  }

  async function getParentMenu() {
    const { success, data } = await menuTreeApi({})
    if (success) {
      const flattenTreeMenu = tools.treeToList(data) as MenuDetailVO[]
      const dirFlattenTreeMenu = flattenTreeMenu.filter((item) => item.menuType === 'M')
      return tools.listToTree(dirFlattenTreeMenu, { pid: 'parentId', id: 'menuId' })
    }
    return []
  }

  async function onModalFinished() {
    const values = (await form.validateFields()) as MenuDTO
    const menuId = initialValues?.menuId
    set(values, 'isShow', values?.isShow ? 1 : 0)
    set(values, 'status', values?.status ? 1 : 0)
    set(values, 'parentId', values?.parentId ?? 0)
    const { success } = menuId
      ? await menuUpdateApi({ ...values, menuId })
      : await menuCreateApi(values)
    if (success) {
      message.success(menuId ? '编辑菜单成功' : '新增菜单成功')
      onFinished?.()
      onClose?.()
    }
  }

  return (
    <BasicModal
      width={500}
      loading={loading}
      form={form as ProFormInstance}
      title={modalTitle}
      register={register}
      layout="horizontal"
      labelCol={{ span: 4 }}
      onFinish={onModalFinished}
    >
      {/* 父菜单ID */}
      <ProFormTreeSelect
        name="parentId"
        label="父菜单ID"
        placeholder="请输入父菜单ID"
        request={getParentMenu}
        fieldProps={{
          fieldNames: {
            label: 'menuName',
            value: 'menuId'
          }
        }}
      />

      {/* 菜单名称 */}
      <ProFormText
        name="menuName"
        label="菜单名称"
        rules={[{ required: true, message: '请输入菜单名称' }]}
        placeholder="请输入菜单名称"
      />

      {/* 路由地址 */}
      <ProFormText
        name="path"
        label="路由地址"
        placeholder="请输入路由地址"
        rules={[{ required: true, message: '请输入路由地址' }]}
      />

      {/* 组件路径 */}
      <ProFormText name="component" label="组件路径" placeholder="请输入组件路径" />

      {/* 菜单类型 */}
      <ProFormSelect
        name="menuType"
        label="菜单类型"
        initialValue={'C'}
        rules={[{ required: true, message: '请选择菜单类型' }]}
        options={[
          { label: '目录', value: 'M' },
          { label: '菜单', value: 'C' },
          { label: '按钮', value: 'F' }
        ]}
        placeholder="请选择菜单类型"
      />

      <ProFormDependency name={['menuType']}>
        {({ menuType }) => {
          return (
            menuType !== 'M' && (
              <>
                <ProFormText
                  name="url"
                  label="请求地址"
                  placeholder="请输入请求地址"
                  rules={[{ required: true, message: '请输入请求地址' }]}
                />
                <ProFormText
                  name="perms"
                  label="权限标识"
                  placeholder="请输入权限标识"
                  rules={[{ required: true, message: '请输入权限标识' }]}
                />
              </>
            )
          )
        }}
      </ProFormDependency>

      {/* 显示顺序 */}
      <ProFormDigit
        name="menuSort"
        label="显示顺序"
        placeholder="请输入显示顺序"
        initialValue={0}
      />

      {/* 菜单图标 */}
      <ProFormText name="icon" label="菜单图标" placeholder="请输入菜单图标" />

      {/* 是否显示 */}
      <ProFormSwitch name="isShow" label="是否显示" initialValue={1} />

      {/* 菜单状态 */}
      <ProFormSwitch name="status" label="是否禁用" initialValue={1} />

      {/* 备注 */}
      <ProFormTextArea name="remark" label="备注" placeholder="请输入备注" />
    </BasicModal>
  )
}
